package com.a51integrated.sfs2x;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;

import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.SFSObject;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import com.smartfoxserver.v2.extensions.ExtensionLogLevel;

public class NewGameRequestHandler extends BaseClientRequestHandler {

	@Override
	public void handleClientRequest(User player, ISFSObject params) {
		// TODO Auto-generated method stub

		Room last_room = player.getLastJoinedRoom();
		if (last_room != null)
		{			
			// Get password from DB.
			IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
			Connection connection;
			try
			{
				// Grab a connection from the DBManager connection pool.
				connection = dbManager.getConnection();
				Random randGen = new Random();
				int rand = randGen.nextInt();
				rand = (rand < 0)?(-rand):(rand);
				String newgamename = "Game#" + rand;
				
				// Insert a new game into the games table. Use a random name.
				PreparedStatement stmt = connection.prepareStatement("INSERT INTO games(names, numconnected) VALUES (?, 0)");
				stmt.setString(1, newgamename);
				boolean res = stmt.execute();
				boolean accepted = (stmt.getUpdateCount() >= 1);
				
				// If the new game request has been accepted, two new tables must be created for this game.
				// The new tables are called 'game_gamename_players' and 'game_gamename_gamedata where gamename equals the game name as it appears in the games table.
				stmt = connection.prepareStatement( "CREATE TABLE `game_" + newgamename + "_players` (`player` varchar( 50 ) NOT NULL default '', `points` int( 11 ) NOT NULL default 0) Engine=myISAM" );
				res = stmt.execute();	// TODO: Ensure the table was created.
				stmt = connection.prepareStatement( "CREATE TABLE `game_" + newgamename + "_gamedata` (`node` int( 11 ), `owner` varchar( 50 ) NOT NULL default '') Engine=myISAM" );
				res = stmt.execute();	// TODO: Ensure the table was created.
				
				// Return connection to the DBMananger connection pool.
				connection.close();

				// Send query in correct format back to the user.
				ISFSObject response = new SFSObject();
				response.putUtfString("gamename", newgamename);
				response.putBool("accepted", accepted);

				// Send the data back to the user.
				send("newgame", response, player);
			}
			catch(SQLException e)
			{
				trace(ExtensionLogLevel.WARN, "SQL Failed: " + e.toString());
			}
		}
		else
		{
			trace("No valid room found for user request.");
		}
	}

}
